//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Printing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using DevExpress.Xpf.Docking;
using GenericGridControl;
using OpenLS.Core;
using OpenLS.Spreadsheet.Internals;
using OpenLS.Spreadsheet.UI.Internals.Resources;
using OpenLS.UI;
using System.Windows.Threading;
using OpenLS.Spreadsheet.UI.Internals;
using System.Globalization;
using System.Threading;
using OpenLS.Spreadsheet.Formats;

//\\using Microsoft.Win32;


namespace OpenLS.Spreadsheet.UI
{
    /// <summary>
    /// Represents the main window of a spreadsheet application.
    /// </summary>

    public partial class SpreadsheetWindow
    {

       
        
        public SpreadsheetWindow()
        {
#if DEBUG
            Debug.Listeners.Add(new TextWriterTraceListener("trace.txt"));
            Debug.WriteLine("in SpreadsheetWindow.ctor");
#endif
            InitializeComponent();
            
#if DEBUG2
            Debugging.FocusHelper.StartShowFocusTimer(this);
            Keyboard.AddPreviewGotKeyboardFocusHandler(this, (o, args) => Debug.WriteLine(string.Format("Preview Got focus|{0}|{1}|{2}", args.Source, args.OldFocus, args.OriginalSource)));
            Keyboard.AddPreviewLostKeyboardFocusHandler(this, (o, args) => Debug.WriteLine(string.Format("Preview Lost focus|{0}|{1}|{2}", args.Source, args.OldFocus, args.OriginalSource)));
            Keyboard.AddGotKeyboardFocusHandler(this, (o, args) => Debug.WriteLine(string.Format("Got focus|{0}|{1}|{2}", args.Source, args.OldFocus, args.OriginalSource)));
            Keyboard.AddLostKeyboardFocusHandler(this, (o, args) => Debug.WriteLine(string.Format("Lost focus|{0}|{1}|{2}", args.Source, args.OldFocus, args.OriginalSource)));
#endif
#if DEBUG
            Debug.WriteLine("After InitializeComponent");
            this.SizeChanged += new SizeChangedEventHandler(SpreadsheetWindow_SizeChanged);
#endif
            SetRecentlyUsedDocumentManager(this, RecentlyUsedDocumentManager.Retrieved);
            PreviewKeyDown += onWindowPreviewKeyDown;
            PreviewMouseDown += onWindowPreviewMouseDown;
            KeyDown += onWindowKeyDown;
            // ResourceDebug.Flush();
           //\\ Debug.WriteLine("creating SpreadsheetWindow 3, Width = " + this.Width);

            ForcedCulture.StoreLanguage("en-US");
            
        }

       
#if DEBUG
        void SpreadsheetWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
           
        }

#endif


        void onWindowKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Tab:
                    //\\Debug.WriteLine("Before Tap");
                    if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
                    {
                        using (new DocumentLock(Documents))
                        {
                            ICollectionView view = CollectionViewSource.GetDefaultView(Documents);
                            int index = Documents.IndexOf((DocumentContainer)view.CurrentItem);
                            index++;
                            if (index >= Documents.Count)
                                index = 0;
                            if (index < Documents.Count)
                                view.MoveCurrentTo(Documents[index]);
                        }
                    }
                    if (e.KeyboardDevice.Modifiers == ModifierKeys.Shift)
                    {
                        using (new DocumentLock(Documents))
                        {
                            ICollectionView view = CollectionViewSource.GetDefaultView(Documents);
                            int index = Documents.IndexOf((DocumentContainer)view.CurrentItem);
                            index--;
                            if (index < 0)
                                index = Documents.Count - 1;
                            if (index < Documents.Count)
                                view.MoveCurrentTo(Documents[index]);
                        }
                    }
                    //\\Debug.WriteLine("End Tap");
                    break;
            }
        }



        public static RecentlyUsedDocumentManager GetRecentlyUsedDocumentManager(DependencyObject obj)
        {
            return (RecentlyUsedDocumentManager)obj.GetValue(RecentlyUsedDocumentManagerProperty);
        }

        public static void SetRecentlyUsedDocumentManager(DependencyObject obj, RecentlyUsedDocumentManager value)
        {
            obj.SetValue(RecentlyUsedDocumentManagerProperty, value);
        }

        // Using a DependencyProperty as the backing store for RecentlyUsedDocumentManager.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty RecentlyUsedDocumentManagerProperty =
            DependencyProperty.RegisterAttached("RecentlyUsedDocumentManager", typeof(RecentlyUsedDocumentManager), typeof(SpreadsheetWindow), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));


      

        void onWindowPreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (SpreadsheetElement.GetOperation(this) != null)
                e.Handled = true;
        }

        void onWindowPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (SpreadsheetElement.GetOperation(this) == null)
                return;
            if (e.Key == Key.Escape)
            {
                SpreadsheetElement.GetOperation(this).Cancelled = true;
                SpreadsheetElement.GetOperation(this).CancelAsync();
            }
            else
                e.Handled = true;
        }
        void onDrop(object sender, DragEventArgs args)
        {
            if (args.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var fileNames = (string[])args.Data.GetData(DataFormats.FileDrop);
                foreach (string fileName in fileNames)
                {
                    openFile(fileName);
                }
            }

        }

        void onSwitchWindow(object sender, ExecutedRoutedEventArgs args)
        {
            if (args.Parameter != null)
            {
                using (new DocumentLock(Documents))
                {
                    CollectionViewSource.GetDefaultView(Documents).MoveCurrentTo(args.Parameter);
                }
            }
            else
            {
                int index = Documents.IndexOf(getCurrentDocument2());
                index++;
                if (index >= Documents.Count)
                    index = 0;
                using (new DocumentLock(Documents))
                {
                    //\\Debug.WriteLine("Before switch");
                    var view = CollectionViewSource.GetDefaultView(Documents);
                    SpreadsheetDocument currentDocument = ((DocumentContainer) view.CurrentItem).Document;
                    SpreadsheetDocument newDocument = Documents[index].Document;
                    this.InChange = true;

                    CollectionViewSource.GetDefaultView(Documents).MoveCurrentTo(Documents[index]);
                    //\\Debug.WriteLine("After switch");
                    this.InChange = false;


                }
            }
            updateTitle();
            args.Handled = true;
        }

        internal bool InChange = false;

        public class DocumentLock : IDisposable
        {
            private readonly ObservableCollection<DocumentContainer> _documents;

            public DocumentLock(ObservableCollection<DocumentContainer> documents)
            {
                _documents = documents;
                foreach (var document in documents)
                {
                    document.GetIsDirty();
                }
            }

            public void Dispose()
            {
                foreach (var document in _documents)
                {
                    document.ResetIsDirty();
                }
            }
        }
        void onExit(object sender, ExecutedRoutedEventArgs args)
        {
            Application.Current.Shutdown();
            args.Handled = true;
        }
        void onOptions(object sender, ExecutedRoutedEventArgs args)
        {
            var w = new OptionsWindow();
            if (w.ShowDialog().GetValueOrDefault())
            {
                // SJE: To do => reactivate the language selection box
                // ForcedCulture.StoreLanguage(w.SelectedCultureName);
                var resourceDictionary = w.SelectedSkin;
                if (resourceDictionary != null)
                    SkinManager.SetSkin(resourceDictionary);
            }
        }
        void onClosing(object sender, CancelEventArgs args)
        {
            savePreferences();
            foreach (DocumentContainer doc in Documents)
            {
                bool canceled;
                if (doc.Document == null)
                    continue;
                closeDocument(doc.Document, out canceled);
                if (canceled)
                {
                    args.Cancel = true;
                    break;
                }
            }
        }
        void closeDocument(SpreadsheetDocument doc, out bool canceled)
        {
            Workbook wb = doc.Workbook;
            canceled = false;
            if (wb.Document.IsDirty)
            {
                //args.Cancel = true;
                switch (MessageBox.Show(string.Format(UIStringTable.SaveFile, doc.Name), "Office Spreadsheet", MessageBoxButton.YesNoCancel))
                {
                    case MessageBoxResult.Cancel:
                        canceled = true;
                        return;
                    case MessageBoxResult.Yes:
                        canceled = true;
                        if (wb.Document.FileName != null)
                        {
                            saveAs(wb.Document, wb.Document.FileName);
                            canceled = false;
                        }
                        else
                        {
                            var d = new SaveFileDialog();
                            setupSaveDialog(d, wb.Document);
                            if (d.ShowDialog(this).GetValueOrDefault())
                            {
                                try
                                {
                                    //\\wb.Document.SaveAs(d.FileName);
                                    saveAs(wb.Document, d.FileName);
                                    canceled = false;
                                }
                                catch (Exception e)
                                {
                                    MessageBox.Show(e.Message);
                                }
                            }
                        }

                        break;
                    case MessageBoxResult.No:
                        canceled = false;
                        return;
                    default: throw new NotSupportedException();

                }
            }
        }
        static void saveAs(OfficeDocument doc, string fileName)
        {
            doc.FileName = fileName;
            using (var f = new BackupFile(fileName))
            {
                try
                {
                    if (doc.FileName != null && File.Exists(doc.FileName))
                    {
                        try
                        {
                            File.Delete(doc.FileName);
                        }
                        catch (IOException)
                        {
                        }
                    }
                    doc.SaveAs(doc.FileName);
                    f.Commit();
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }
            }
        }


        static string getAvailableFileName(string dirName, string fileName, string extension)
        {
            int i = 1;
            while (true)
            {
                string s = Path.Combine(dirName, fileName + i + "." + extension);
                if (!File.Exists(s))
                    return s;
                i++;

            }
        }

        void onAlways(object sender, CanExecuteRoutedEventArgs args)
        {
            args.CanExecute = true;
        }

        void onNew(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
        {

           //\\ Debug.WriteLine("Creating document");
            SpreadsheetDocument doc = SpreadsheetDocument.Create();
            for (int i = 1; ; i++)
            {
                string bookName = StringTable.Book + i;
                bool contained = false;
                contained = Enumerable.Any(Documents,
                                           container =>
                                           (container.Document != null &&
                                            string.Compare(container.Document.Name, bookName, true) == 0));
                if (!contained)
                {
                    doc._defaultName = bookName;
                    break;
                }
            }
          //\\  Debug.WriteLine("Adding document");
            Documents.Add(new DocumentContainer(doc));
        }

        void onOpen(object sender, ExecutedRoutedEventArgs args)
        {
            try
            {
           
                if (args.Parameter is string)
                {
                    openFile(args.Parameter as string);
                    return;
                }
                var d = new OpenFileDialog
                            {
                                FileName = _oldFileName,
                                DefaultExt = "*.xlsx",
                                Filter = UIStringTable.OpenFileFilter,
                                AddExtension = true,
                                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                RestoreDirectory = true
                            };

                if (d.ShowDialog(this).GetValueOrDefault())
                {
                    openFile(d.FileName);
                    _oldFileName = d.FileName;
                }
            }
            catch (Exception exp)
            {
                if (MessageBox.Show(exp.Message, "Do you want more info", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    Debug.WriteLine(exp.ToString());
                    MessageBox.Show("More info saved in file " + DebugTraceListener.Instance.FileName);
                    MessageBox.Show(exp.ToString());
                }
            }
        }
        string _oldFileName;

        internal void openFile(string fileName)
        {
            var container = Enumerable.FirstOrDefault(Documents,
                                                     dd => string.Compare(dd.Document.FileName, fileName) == 0);
            if (container != null)
            {
                CollectionViewSource.GetDefaultView(Documents).MoveCurrentTo(container);
                return;
            }
            GC.Collect(GC.MaxGeneration);
            GC.Collect(0);
            string extension = Path.GetExtension(fileName).ToLower();
            SpreadsheetDocument doc = null;
            switch (extension)
            {
                case ".xls":
                    {
                        doc = new BiffFormat().Open(fileName);
                        addRecentlyUsedDocument(fileName);

                        Documents.Add(new DocumentContainer(doc));
                    }
                    break;
                case ".tab":
                case ".tsv":
                    doc = new TsvFormat().Open(fileName);
                    Documents.Add(new DocumentContainer(doc));
                    break;
                case ".csv":
                    doc = new CsvFormat().Open(fileName);
                    Documents.Add(new DocumentContainer(doc));
                    break;


                default:
                    var currentOperation = new BackgroundOperation (this.Dispatcher)
                                               {
                                                   WorkerSupportsCancellation = true,
                                                   WorkerReportsProgress = true
                                               };
                    CultureInfo cu = Thread.CurrentThread.CurrentCulture;
                    CultureInfo cui = Thread.CurrentThread.CurrentUICulture;
                    currentOperation.DoWork += delegate
                    {
                        try
                        {
                            Thread.CurrentThread.CurrentCulture = cu;
                            Thread.CurrentThread.CurrentUICulture = cui;
//                            Debug.WriteLine("Opening in culture" + CultureInfo.CurrentCulture.Name);
                            doc = SpreadsheetDocument.Open(fileName, SpreadsheetContext.Default, currentOperation);
                            
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message);
                        }
                    };
                    currentOperation.RunWorkerCompleted +=
                    delegate
                    {
                        if (!currentOperation.Cancelled && doc != null)
                        {
                            addRecentlyUsedDocument(fileName);
                            Documents.Add(new DocumentContainer(doc));
                        }
                        SpreadsheetElement.SetOperation(this, null);
                        // We must wait that the document has been added to the SpreadsheetWindow document before inserting big data tables
                        if (doc == null)
                            return;
                        doc.Workbook.DisplayDataTables();
                        
                        savePreferences();
                    };
                    SpreadsheetElement.SetOperation(this, currentOperation);
                    currentOperation.RunWorkerAsync();
                    break;
            }
        }

        private void addRecentlyUsedDocument(string fileName)
        {
            RecentlyUsedDocumentManager man = GetRecentlyUsedDocumentManager(this);
            if (man == null)
            {
                man = RecentlyUsedDocumentManager.Retrieved;
                SetRecentlyUsedDocumentManager(this, man);
            }
            man.AddRecentlyUsedDocument((fileName));
        }


        private ObservableCollection<DocumentContainer> _documents;
        public ObservableCollection<DocumentContainer> Documents
        {
            get
            {
                if (_documents == null)
                {
                    _documents = new ObservableCollection<DocumentContainer>();
                    DataContext = _documents;
                    SpreadsheetElement.SetDocuments(this, _documents);
                    _documents.CollectionChanged += documentsCollectionChanged;
                }
                return _documents;
            }
        }

        void documentsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                using (new DocumentLock(Documents))
                {
                    CollectionViewSource.GetDefaultView(Documents).MoveCurrentTo(e.NewItems[0]);
                }
            }
            updateTitle();
            DocumentContainer doc = getCurrentDocument2();
            doc.Document.Workbook.TableAdded += Workbook_TableAdded;
            doc.Document.Workbook.TableDefinitionLoaded += Workbook_TableDefinitionLoaded;
        }

        void Workbook_TableDefinitionLoaded(object sender, TableDefinitionLoadedEventArgs e)
        {
            
            
            BigDataTableControl dynamicControl = new BigDataTableControl();
            dynamicControl.DefineTableJsonFormat(e.tableDefinition);

            Thickness margin = dynamicControl.Margin;
            margin.Bottom = 30;
            dynamicControl.Margin = margin;

            this.SpreadsheetContentGroup.Items.Add(dynamicControl);
        }

        void Workbook_TableAdded(object sender, TableEventArgs e)
        {
            if (e.TableAction == "BIGDATATABLE")
            {
                try
                {
                    BigDataTableControl dynamicControl = new BigDataTableControl();
                    // dynamicControl.Data
                    // dynamicControl.CurrentTable = e.CurrentTable;
                    dynamicControl.DefineTableJsonFormat(e.CurrentTable.JsonTableDefinition);
                    dynamicControl.CurrentWorkbook = e.CurrentWorkbook;
                    // dynamicControl.CurrentWorkbook = e.CurrentWorkbook;

                    this.SpreadsheetContentGroup.Items.Add(dynamicControl);
                    int tabCount = this.SpreadsheetContentGroup.Items.Count;
                    this.SpreadsheetContentGroup.SelectedTabIndex = tabCount - 1;

                }
                catch (Exception ex)
                {
                    var message = ex.Message;
                }
            }
            else if (e.TableAction == "MARKETDATA")
            {
                try
                {
                    MarketDataTableControl dynamicControl = new MarketDataTableControl();
                    // dynamicControl.Data
                    // dynamicControl.CurrentTable = e.CurrentTable;
                    dynamicControl.DefineTableJsonFormat(e.CurrentTable.JsonTableDefinition);
                    dynamicControl.CurrentWorkbook = e.CurrentWorkbook;
                    // dynamicControl.CurrentWorkbook = e.CurrentWorkbook;

                    this.SpreadsheetContentGroup.Items.Add(dynamicControl);
                    int tabCount = this.SpreadsheetContentGroup.Items.Count;
                    this.SpreadsheetContentGroup.SelectedTabIndex = tabCount - 1;

                }
                catch (Exception ex)
                {
                    var message = ex.Message;
                }
            }
        }


        private void updateTitle()
        {
            DocumentContainer doc = getCurrentDocument2();
            if (doc != null && doc.Document != null)
                Title = doc.Document.Name + " - Spreadsheet";
            else
                Title = "Spreadsheet";
            var label = (Label)Template.FindName("titleBar", this);
            if (label != null)
                label.Content = Title;

            
        }

        DocumentContainer getCurrentDocument2()
        {
            return (DocumentContainer)CollectionViewSource.GetDefaultView(Documents).CurrentItem;
        }
        SpreadsheetDocument getCurrentDocument()
        {
            DocumentContainer c = getCurrentDocument2();
            return c == null ? null : c.Document;
        }
        void onSave(object sender, ExecutedRoutedEventArgs args)
        {
            DocumentContainer c = getCurrentDocument2();
            if (c == null)
                return;
            SpreadsheetDocument doc = c.Document;
            this.CommitText();
            if (doc.FileName == null)
            {
                onSaveAs(sender, args);
                return;
            }
            var extension = Path.GetExtension(doc.FileName);
            if (extension.ToString() == ".xls")
                doc.FileName += "x";
            using (var f = new BackupFile(doc.FileName))
            {
                try
                {
                    try
                    {
                        File.Delete(doc.FileName);
                    }
                    catch (IOException)
                    {
                    }
                    try
                    {
                        GetRecentlyUsedDocumentManager(this).AddRecentlyUsedDocument(doc.FileName);
                    }
                    catch
                    {
                    }

                    using (Package p = Package.Open(doc.FileName))
                    {
                        doc.WritePackage(p);
                    }
                    f.Commit();
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }
            }
        }

        private void Slider_Scale_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            // TimeLine3.UnitSize = Slider_Scale.Value;
            // TimeLine2.UnitSize = Slider_Scale.Value;
        }

        private void CommitText()
        {
            SpreadsheetElement.CommitText(this.documentsContainer);
        }

        void onSaveAsXps(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
        {
            CommitText();
            var d = new SaveFileDialog();
            if (d.ShowDialog(this).GetValueOrDefault())
            {
                XpsDocument doc = new XpsDocument(d.FileName, FileAccess.Write);
                XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
                var collator = writer.CreateVisualsCollator();
                SpreadsheetPrinter.WriteWorksheet(collator, (Worksheet)SpreadsheetElement.GetWorkbook(this).View.ActiveSheet);
//                var collator = writer.CreateVisualsCollator();


  //              Workbook wb = SpreadsheetElement.GetWorkbook(this);
    //            SpreadsheetPrinter.WriteWorksheet(collator, (Worksheet)wb.View.ActiveSheet);
                doc.Close();
            }
        }
        void onSaveAs(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
        {
            CommitText();
            SpreadsheetDocument doc = getCurrentDocument();
            var d = new SaveFileDialog();
            setupSaveDialog(d, doc);
            if (d.ShowDialog(this).GetValueOrDefault())
            {
                try
                {
                    string extension = Path.GetExtension(d.FileName).ToLower().Trim('.');
                    switch (extension)
                    {
                        case "xlsx":

                            using (Package p = Package.Open(d.FileName, FileMode.Create))
                            {
                                doc.WritePackage(p);
                                doc.FileName = d.FileName;
                                try
                                {
                                    GetRecentlyUsedDocumentManager(this).AddRecentlyUsedDocument(doc.FileName);
                                }
                                catch (Exception)
                                {
                                }
                                updateTitle();
                            }
                            break;
                        case "xps":
                            if (File.Exists(d.FileName))
                                File.Delete(d.FileName);
                            var xpsDocument = new XpsDocument(d.FileName, FileAccess.ReadWrite);
                            XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
                            var collator = writer.CreateVisualsCollator();

                            Workbook wb = SpreadsheetElement.GetWorkbook(this);
                            SpreadsheetPrinter.WriteWorksheet(collator, (Worksheet)wb.View.ActiveSheet);
                            xpsDocument.Close();
                            break;
                        case "xls":
                            {
                                new BiffFormat().Save(doc, d.FileName);
                                updateTitle();
                            }
                            break;
                        default:
                            throw new NotImplementedException(extension);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

        private static void setupSaveDialog(FileDialog d, OfficeDocument doc)
        {
            d.AddExtension = true;
            d.Filter = UIStringTable.SaveFileFilter;
            d.DefaultExt = "xlsx";
            d.FileName = doc.FileName ?? getAvailableFileName(Environment.CurrentDirectory, "Workbook", "xlsx");
        }
        void onClose(object sender, ExecutedRoutedEventArgs args)
        {
            savePreferences();
            var doc = (DocumentContainer)(args.Parameter ?? getCurrentDocument2());
            if (doc == null)
                return;
            bool canceled;
            closeDocument(doc.Document, out canceled);
            if (canceled)
                return;
            Documents.Remove(doc);
            GC.Collect(GC.MaxGeneration);
        }

        private void savePreferences()
        {
            var i = (Preferences)EditionElement.GetPreferences(this);
            if (i != null)
                i.Save(Enumerable.Select(Documents, c => c.Document));
        }


        void onPrint(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
        {
            var d = new PrintDialog();
            if (d.ShowDialog().GetValueOrDefault())
            {
                try
                {
                    SpreadsheetPrinter.SendWorksheet(d.PrintQueue, (Worksheet) SpreadsheetElement.GetWorkbook(this).View.ActiveSheet);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                /*PrintQueue q = d.PrintQueue;
                XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(q);
                var collator = writer.CreateVisualsCollator();


                try
                {
                    Workbook wb = SpreadsheetElement.GetWorkbook(this);

                    SpreadsheetPrinter.WriteWorksheet(collator, (Worksheet)wb.View.ActiveSheet);
                    q.Commit();
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }*/

            }
        }

        void onCanSave(object sender, CanExecuteRoutedEventArgs args)
        {
            args.CanExecute = getCurrentDocument() != null;
        }
        class Disabler : IDisposable
        {
            public Disabler(Window w)
            {
                w.IsEnabled = false;
                _cursor = w.Cursor;
                w.Cursor = Cursors.Wait;
                _window = w;
            }
            #region IDisposable Members

            private readonly Cursor _cursor;
            private readonly Window _window;
            public void Dispose()
            {
                _window.IsEnabled = true;
                _window.Cursor = _cursor;
            }

            #endregion
        }

        void onLoaded(object sender, RoutedEventArgs args)
        {
            var timer = new DispatcherTimer(DispatcherPriority.ApplicationIdle);
            timer.Tick +=
                delegate
                {
                    using (new Disabler(this))
                    {
                       //\\ Debug.WriteLine("Adding workbook resources");
                        Resources.MergedDictionaries.Add(new WorkbookResources());
                        string[] cmdLineArgs = Environment.GetCommandLineArgs();
                        Preferences preferences = Preferences.Retrieved;
                        EditionElement.SetPreferences(this, preferences);
                        if (cmdLineArgs.Length > 1)
                        {
                            /*
                            try
                            {
                                for (int i = 1; i < cmdLineArgs.Length; i++)
                                {
                                    openFile(cmdLineArgs[i]);
                                }
                            }

                            catch (Exception)
                            {
                                onNew(this, null);
                            }
                            */
                        }
                        else
                        {
                            bool fileOpened = false;
                            if (preferences.OpenPreviousDocuments)
                            {
                                foreach (string fileName in preferences.DocumentNames)
                                {
                                    try
                                    {
                                        if (File.Exists(fileName))
                                        {
                                            fileOpened = true;
                                            openFile(fileName);
                                        }
                                    }
                                    catch
                                    {
                                        Debug.WriteLine(string.Format("Unable to open {0}", fileName));
                                    }
                                }
                            }
                            if (!fileOpened)
                            {
                                onNew(this, null);
                            }
                        }
                      //\\  Debug.WriteLine("Done");
                        timer.Stop();
                        //ResourceDebug.Flush();
                        IsEnabled = true;
                        //ResourceDebug.Flush();
                    }
                }
                ;
            timer.Start();
        }

        private void onPrintPreview(object sender, ExecutedRoutedEventArgs e)
        {
            Workbook wb = SpreadsheetElement.GetWorkbook(this);
            var ws = (Worksheet)wb.View.ActiveSheet;
            var window = new PrintPreviewWindow(ws);
            PropertyHelper.TransferProperties(this, window);
            window.ShowDialog();
        }
    }
}